package com.shen.thread.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestCreate {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class aClass = Class.forName("com.shen.reflection.User");
//        User user = (User) aClass.newInstance();//需要无参构造
//        System.out.println(user);
//        //通过构造器创建对象
//        Constructor constructor = aClass.getDeclaredConstructor(int.class, String.class, int.class);
//        User bin = (User) constructor.newInstance(1, "bin", 18);
//        System.out.println(bin);

        //通过反射调用方法
        User user = (User) aClass.newInstance();
        //通过反射获取方法
        Method setName = aClass.getDeclaredMethod("setName", String.class);
        //invoke:激活  （对象，“方法的值”）
        setName.invoke(user, "bin");
        System.out.println(user.getName());

        //通过反射操作属性
        User user2 = (User) aClass.newInstance();
        Field name = aClass.getDeclaredField("name");
        //关闭程序的安全检测
        name.setAccessible(true);
        name.set(user2, "bin2");
        System.out.println(user2.getName());
    }
}
